package slim3.controller.member.todo;

import java.util.Iterator;
import java.util.logging.Logger;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Errors;
import org.slim3.controller.validator.Validators;
import org.slim3.util.StringUtil;

import slim3.controller.SimpleResponse;
import slim3.dao.CategoryDao;
import slim3.dao.TaskDao;
import slim3.model.Category;
import slim3.model.Task;

public class AddController extends Controller {

    @SuppressWarnings("unused")
    private static final Logger logger =
        Logger.getLogger(AddController.class.getName());

    private TaskDao dao = new TaskDao();
    private CategoryDao categoryDao = new CategoryDao();

    @Override
    public Navigation run() {
        if (!validate()) {
//            requestScope("taskList", dao.findAll(false, categoryDao));
//            requestScope("doneList", dao.findAll(true, categoryDao));

            SimpleResponse resp = new SimpleResponse();
            resp.status = "error";
            Errors errors = this.errors;
            for (Iterator<String> key = errors.keySet().iterator(); key.hasNext();) {
                resp.message += errors.get(key.next());
            }
            requestScope("json", resp);
            return forward("/json/encode.jsp");
        }
        Task t = null;
        if (StringUtil.isEmpty(asString("key"))) {
            // 追加
            t = new Task();
            setTask(t);
            t.setCategoryKey(getCategoryKey());
            System.out.println("cate key: " + t.getCategoryKey());
            dao.begin();
            t = dao.makePersistent(t);
            dao.commit();
        } else {
            // 更新
            String categoryKey = getCategoryKey();
            System.out.println("cate key: " + categoryKey);
            dao.begin();
            t = dao.find(key());
            setTask(t);
            t.setCategoryKey(categoryKey);
            dao.commit();
        }
//        requestScope("taskList", dao.findAll(false, categoryDao));
//        requestScope("doneList", dao.findAll(true, categoryDao));
//        SimpleResponse resp = new SimpleResponse();
//        resp.status = "ok";
//        requestScope("json", resp);
//        return forward("/json/encode.jsp");
        requestScope("e", t);
        return forward("add.jsp");
    }

    protected boolean validate() {
        Validators v = new Validators(request);
        v.add("dueDate", v.required());
        v.add("dueDate", v.dateType("yyyy/MM/dd"));
        v.add("category", v.required());
        v.add("content", v.required());
        return v.validate();
    }

    private void setTask(Task t) {
        t.setContent(asString("content"));
        t.setDueDate(asDate("dueDate", "yyyy/MM/dd"));
        t.setFinished(false);
    }
    private String getCategoryKey() {
        String category = asString("category");
        if (category == null) {
            return null;
        }
        Category c = categoryDao.findByName(category);
        if (c == null) {
            c = new Category();
            c.setName(asString("category"));
            c = categoryDao.makePersistentInTx(c);
            c.getKey();
        }
        return c.getKey();
    }
}
